package com.syf.kit.es.config;

import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.syf.kit.es.core.SyEsClient;
import com.syf.kit.es.core.SyEsObjectClient;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

/**
 * Elasticsearch自动配置类
 */
@Configuration
@EnableConfigurationProperties(SyEsProperties.class)
public class SyEsAutoConfig {

    @Bean
    @ConditionalOnMissingBean
    public RestHighLevelClient restHighLevelClient(SyEsProperties properties) {
        // 创建HttpHost
        HttpHost httpHost = new HttpHost(
                properties.getHost(),
                properties.getPort(),
                properties.getScheme());

        // 创建RestClientBuilder
        RestClientBuilder builder = RestClient.builder(httpHost);

        // 配置连接超时
        builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                .setConnectTimeout(properties.getConnectTimeout())
                .setSocketTimeout(properties.getSocketTimeout())
                .setConnectionRequestTimeout(properties.getConnectionRequestTimeout()));

        // 配置连接池
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder
                    .setMaxConnTotal(properties.getMaxConnTotal())
                    .setMaxConnPerRoute(properties.getMaxConnPerRoute());
            // 新增：如果配置了用户名和密码，则设置 Basic Auth 认证
            if (StrUtil.isNotBlank(properties.getUsername()) && StrUtil.isNotBlank(properties.getPassword())) {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword()));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            return httpClientBuilder;
        });

        return new RestHighLevelClient(builder);
    }

    @Bean
    @ConditionalOnMissingBean
    public ElasticsearchClient elasticsearchClient(RestHighLevelClient restHighLevelClient) {
        // 创建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restHighLevelClient.getLowLevelClient(),
                new JacksonJsonpMapper());

        // 创建API客户端
        return new ElasticsearchClient(transport);
    }

    @Bean
    @ConditionalOnMissingBean
    public ElasticsearchOperations elasticsearchOperations(RestHighLevelClient restHighLevelClient) {
        return new ElasticsearchRestTemplate(restHighLevelClient);
    }

    @Bean
    @ConditionalOnMissingBean
    public SyEsClient syEsClient(ElasticsearchClient elasticsearchClient) {
        return new SyEsClient(elasticsearchClient);
    }

    @Bean
    @ConditionalOnMissingBean
    public SyEsObjectClient syEsObjectClient(ElasticsearchOperations elasticsearchOperations) {
        return new SyEsObjectClient(elasticsearchOperations);
    }
}